# -*- python -*-
# SPDX-License-Identifier: AGPL-3.0-or-later
# SPDX-FileCopyrightText: 2022 grommunio GmbH
# This file is part of Gromox.

from __future__ import print_function
import binascii
import json
import kopano
import struct
import sys

init_server = kopano.Server()
server_list = set()
faulty = False
for user in init_server.users(remote=True, system=False, hidden=True,
    inactive=True):
	server_list.add(user.home_server)

print("[")
for server_name in server_list:
	uri = "https://%s:237/kopano" % server_name
	server = None
	try:
		server = kopano.Server(server_socket=uri,
		         sslkey_file=init_server.sslkey_file)
	except:
		faulty = True
		continue
	sguid = server.guid.lower()
	for user in server.users(remote=True, system=False, hidden=True,
	    inactive=True):
		# 00000000AC21A95040D3EE48B319FBA7533044250100000006000000000100004D6A55784D6A453D00000000
		obj = {
			"sv": sguid,
			"st": user.guid,
			"na": user.name,
			"em": user.email,
			"to": user.email
		}
		if user.userid[0:48] == "00000000AC21A95040D3EE48B319FBA75330442501000000":
			obj["id"] = struct.unpack("<L", binascii.unhexlify(user.userid[56:64]))[0]
		print(json.dumps(obj), ",", sep='')
print("{}]")

if faulty:
	sys.stderr.write("[1;31mNot all servers could be reached[0m\n")
